package com.example.mcdonaldapplication.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mcdonaldapplication.databinding.ActivityUserAllOrderBinding
import com.example.mcdonaldapplication.info.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

class UserAllOrderActivity : AppCompatActivity() {
    private lateinit var binding:ActivityUserAllOrderBinding
    private val serverIp = ServerIP.getIp()
    private val orderList : ArrayList<OrderInfo> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityUserAllOrderBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()

        getOrder()
    }

    private fun getOrder(){
        thread {
            val prefs = getSharedPreferences("user", MODE_PRIVATE)
            val uid = prefs.getInt("uid", 0)
            //post方式提交的数据
            val formBody: FormBody = FormBody.Builder()
                .add("uid", uid.toString())
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIp}/order/queryAll")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJsonOrder(responseData)
        }
    }

    private fun parseJsonOrder(jsonData: String) {
        val gson = Gson()
        val jsonObject = JSONObject(jsonData)
        val data = jsonObject.getString("data")
        if(data != "[]"){
            val typeOf = object : TypeToken<List<OrderInfo>>() {}.type
            val orderInfoList = gson.fromJson<List<OrderInfo>>(data, typeOf)
            for (order in orderInfoList) {
                orderList.add(order)
            }
            runOnUiThread{
                binding.tvNoOrder.visibility = View.GONE
                val layoutManager = LinearLayoutManager(this)
                binding.recyclerViewOrder.layoutManager = layoutManager
                val recycleAdapter = OrderAdapter(orderList)
                binding.recyclerViewOrder.adapter = recycleAdapter
            }
        }else{
            runOnUiThread{
                binding.tvNoOrder.visibility = View.VISIBLE
            }
        }

    }
}